package Team.Listener.Login;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import Packet.Packet;
import Packet.PacketFactory;
import Team.View.Login.*;
import Exception.LoginFailureException;
import Exception.SocketConnectionFailureException;

import Team.Controller.*;
import Team.Model.*;

import Team.Model.Login.*;

import java.io.*;

public class LoginButtonListener implements ActionListener 
{
	public LoginButtonListener(TeamLoginView view, TeamModel model, TeamController controller)
	{
	    this.view = view;
	    this.model = model;
	    this.controller = controller;
	}
    public void actionPerformed(ActionEvent e)
    {
    	view.loginStatusLabel.setText(this.loginingMessage);
        try
        {
        	Initialize initialize = new Initialize(this.model);
        	initialize.initializeSeverIp();
        	initialize.initializeSocket();
        	initialize.initializeObjectOutputStream();
            
        	serverConnect(this.getView().userNameTextField.getText(), 
        			this.getView().passwordField.getPassword().toString());
        }
        catch(SocketConnectionFailureException exception)
        {
        	view.loginStatusLabel.setText(exception.toString());
        	System.out.println("LoginButton exception : SocketConnectionFailureException");
        	exception.printStackTrace();
        }
    }
    
    public void serverConnect(String userName, String password)
    {
    	Packet packet = new PacketFactory().makeClientLoginPacket(PacketFactory.sourceId, PacketFactory.destinationId,
				userName, password, this.model.getClientType());
		
		try
		{				
			this.model.getObjectOutputStream().writeObject(packet);
			
			this.model.getObjectOutputStream().flush();
			
			initialize.initializeObjectInputStream();
		}
		catch(IOException exception)
		{
			exception.printStackTrace();	
		}
    }
    
    public TeamLoginView getView()
    {
        return this.view;	
    }
    
    public TeamModel getModel()
    {
    	return this.model;
    }
    
    private TeamLoginView view;
    private TeamModel model;
    private TeamController controller;
    
    private String loginingMessage = new String("Logining");
    private String loginSuccessfulMessage = new String("Login Successful");
    
    private Initialize initialize;
}
